package com.example.book_libapp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class BookGridView extends Activity {
	// 显示图片的资源
	private static int[] images = { R.drawable.booklist, R.drawable.login };
	Gallery gallery;
	ImageSwitcher is;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery);
		setTitle("这是Gallery和ImageSwitcher的效果");
		gallery = (Gallery) findViewById(R.id.gallery);
		is = (ImageSwitcher) findViewById(R.id.imageSwitcher);
		gallery.setAdapter(new ImageAdapter(this));
		// 让选定的图片在中心显示
		gallery.setSelection(images.length / 2);
		// 为Gallery绑定监听器；
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// 当在Gallery中选定一张图片是 ImageSwitcher同步显示同一张
				// position%images.length 为了让图片循环显示
				is.setImageResource(images[position % images.length]);

			}

			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		is.setFactory(new ImageFactory(this));

	}

	private class ImageAdapter extends BaseAdapter {
		private Context context;

		public ImageAdapter(Context context) {
			this.context = context;
		}

		// 可以return images.lenght(),在这里返回Integer.MAX_VALUE
		// 是为了使图片循环显示
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView iv = new ImageView(context);
			iv.setImageResource(images[position % images.length]);
			iv.setLayoutParams(new Gallery.LayoutParams(90, 90));
			iv.setAdjustViewBounds(true);
			return iv;
		}
	}

	private class ImageFactory implements ViewFactory {
		private Context context;

		public ImageFactory(Context context) {
			this.context = context;
		}

		public View makeView() {
			ImageView iv = new ImageView(context);
			iv.setLayoutParams(new ImageSwitcher.LayoutParams(200, 200));
			return iv;
		}
	}
}